package com.example.testdemoutils.math;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 分组求和
 */
public class GroupBySum {
    public static void main(String[] args) {
        Person p1 = new Person("AAA", new BigDecimal("45.23"));
        Person p2 = new Person("AAA", new BigDecimal("55.43"));
        Person p3 = new Person("BBB", new BigDecimal("65.21"));
        Person p4 = new Person("BBB", new BigDecimal("35.73"));
        List<Person> list = Arrays.asList(p1, p2, p3, p4);
        Map<String, BigDecimal> collect = list.stream().collect(Collectors.groupingBy(Person::getName, Collectors.mapping(Person::getWeight, Collectors.reducing(BigDecimal.ZERO, BigDecimal::add))));
        System.out.println(collect);
    }
}

class Person {
    private String name;
    private BigDecimal weight;

    public Person(String name, BigDecimal weight) {
        this.name = name;
        this.weight = weight;
    }

    public String getName() {
        return name;
    }

    public BigDecimal getWeight() {
        return weight;
    }
}